﻿<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-tabs v-model="activeTab">
			<el-tab-pane label="基本信息" name="main">
				<el-card shadow="hover" class="layout-padding-auto create-form">
					<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>单据信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_BillCode_FormItem" prop="Entity.BillCode">
										<template #label>
											<WtmLabelTooltip label="单据编号" tooltip="单据编号" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.BillCode" disabled clearable class="width100"></el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_Remark_FormItem" prop="Entity.Remark">
										<template #label>
											<WtmLabelTooltip label="备注" tooltip="备注" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.Remark" disabled clearable class="width100"></el-input>
									</el-form-item>
								</el-col>
							</el-row>
						</div>

						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>基本信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_PersonId_FormItem" prop="Entity.PersonId">
										<template #label>
											<WtmLabelTooltip label="员工" tooltip="关联的员工实体" />
										</template>
										<WtmPersonSelector v-model="stateData.vmModel.Entity.PersonId" :disabled="true" :prefill-person="prefillPerson" />
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_StaffNo_FormItem" prop="Entity.StaffNo">
										<template #label>
											<WtmLabelTooltip label="员工工号" tooltip="员工工号" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.StaffNo" disabled clearable class="width100"></el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_Name_FormItem" prop="Entity.Name">
										<template #label>
											<WtmLabelTooltip label="员工姓名" tooltip="员工姓名" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.Name" disabled clearable class="width100"></el-input>
									</el-form-item>
								</el-col>
							</el-row>
						</div>

						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>请假出差信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_LeaveType_FormItem" prop="Entity.LeaveType">
										<template #label>
											<WtmLabelTooltip label="类型" tooltip="请假/出差" />
										</template>
										<el-select v-model="stateData.vmModel.Entity.LeaveType" disabled clearable class="width100">
											<el-option v-for="item in LEAVE_TYPE_OPTIONS" :key="item.value" :value="item.value" :label="item.label"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20" v-if="stateData.vmModel.Entity.LeaveType === '出差'">
									<el-form-item ref="Entity_AffectsAttendance_FormItem" prop="Entity.AffectsAttendance">
										<template #label>
											<WtmLabelTooltip label="是否影响考勤" tooltip="是否影响考勤统计" />
										</template>
										<el-switch v-model="stateData.vmModel.Entity.AffectsAttendance" disabled active-text="是" inactive-text="否"></el-switch>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_StartTime_FormItem" prop="Entity.StartTime">
										<template #label>
											<WtmLabelTooltip label="开始时间" tooltip="开始时间" />
										</template>
										<el-date-picker
											v-model="stateData.vmModel.Entity.StartTime"
											type="datetime"
											disabled
											clearable
											class="width100"
											format="YYYY-MM-DD HH:00"
										></el-date-picker>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_EndTime_FormItem" prop="Entity.EndTime">
										<template #label>
											<WtmLabelTooltip label="结束时间" tooltip="结束时间" />
										</template>
										<el-date-picker
											v-model="stateData.vmModel.Entity.EndTime"
											type="datetime"
											disabled
											clearable
											class="width100"
											format="YYYY-MM-DD HH:00"
										></el-date-picker>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_Days_FormItem" prop="Entity.Days">
										<template #label>
											<WtmLabelTooltip label="天数" tooltip="天数" />
										</template>
										<el-input-number v-model="stateData.vmModel.Entity.Days" disabled clearable class="width100"></el-input-number>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item
										ref="Entity_Reason_FormItem"
										prop="Entity.Reason"
										:rules="[{ required: true, message: '事由为必填项', trigger: 'blur' }]"
									>
										<template #label>
											<WtmLabelTooltip label="事由" tooltip="请假/出差事由" />
										</template>
										<el-input
											v-model="stateData.vmModel.Entity.Reason"
											disabled
											clearable
											class="width100"
											type="textarea"
											:rows="2"
											placeholder="请输入请假/出差事由"
										></el-input>
									</el-form-item>
								</el-col>

								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="SupportingDocumentId_FormItem" prop="Entity.SupportingDocumentId">
										<template #label>
											<WtmLabelTooltip label="证明文件" tooltip="请假/出差证明文件" />
										</template>
										<wtm-upload-file
											v-model="stateData.vmModel.Entity.SupportingDocumentId"
											clearable
											:multi="false"
											:disabled="!stateData.uploadMode"
										></wtm-upload-file>
									</el-form-item>
								</el-col>
							</el-row>
						</div>

						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>流程信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_Approver_FormItem" prop="Entity.Approver">
										<template #label>
											<WtmLabelTooltip label="审批人" tooltip="流程审批人" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.Approver" disabled clearable class="width100"></el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_ApprovalTime_FormItem" prop="Entity.ApprovalTime">
										<template #label>
											<WtmLabelTooltip label="审批时间" tooltip="流程审批时间" />
										</template>
										<el-date-picker v-model="stateData.vmModel.Entity.ApprovalTime" disabled clearable class="width100"></el-date-picker>
									</el-form-item>
								</el-col>
							</el-row>
						</div>

						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>工作信息</span>
							</div>
							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<WtmOrgSelector v-model="stateData.vmModel.Entity.OrgId" label="公司" prop="Entity.OrgId" :auth="false" :disabled="true" />
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<WtmDeptSelector v-model="stateData.vmModel.Entity.GroupId" prop="Entity.GroupId" label="所属部门" :auth="false" :disabled="true" />
								</el-col>
							</el-row>
						</div>

						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>状态信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_BillStatus_FormItem" prop="Entity.BillStatus">
										<template #label>
											<WtmLabelTooltip label="单据状态" tooltip="单据状态" />
										</template>
										<el-select v-model="stateData.vmModel.Entity.BillStatus" disabled clearable class="width100">
											<el-option v-for="item in BILL_STATUS_OPTIONS" :key="item.value" :value="item.value" :label="item.label"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_WorkflowStatus_FormItem" prop="Entity.WorkflowStatus">
										<template #label>
											<WtmLabelTooltip label="工作流状态" tooltip="工作流状态" />
										</template>
										<el-select v-model="stateData.vmModel.Entity.WorkflowStatus" disabled clearable class="width100">
											<el-option v-for="item in WORKFLOW_STATUS_OPTIONS" :key="item.value" :value="item.value" :label="item.label"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
							</el-row>
						</div>
					</el-form>
				</el-card>
			</el-tab-pane>
			<el-tab-pane label="审批信息" key="审批信息">
				<WtmWorkflowTimeline entityType="HengTong.Model.Db.Bill.SysDailyLeaveRequestBill" :entityId="stateData.vmModel.Entity.ID" />
			</el-tab-pane>
		</el-tabs>
	</div>
</template>

<script setup lang="ts" name="message._system.common.vm.edit;false">
import { reactive, ref, getCurrentInstance, onMounted, nextTick, computed, type ComponentInternalInstance } from 'vue';
import { ElMessage } from 'element-plus';
import { SysDailyLeaveRequestBillApi as api } from '/@/views/daily/sysdailyleaverequestbill/api';
import other from '/@/utils/other';
import { useRouter } from 'vue-router';
import { ISysDailyLeaveRequestBillVm } from '/@/views/daily/sysdailyleaverequestbill/api/interface';
import { IViewModel } from '/@/types/common';
import ApproveReasonDialog from '/@/components/approveReason/index.vue';

// 常量定义
const BILL_STATUS = {
	DRAFT: '草稿',
	FORMAL: '正文',
} as const;

const WORKFLOW_STATUS = {
	PENDING: '待提交',
	SUBMITTING: '提交中',
	IN_AUDIT: '审核中',
	COMPLETED: '已完成',
	CANCELLED: '已取消',
} as const;

const LEAVE_TYPE_OPTIONS = [
	{ value: '请假', label: '请假' },
	{ value: '出差', label: '出差' },
] as const;

const BILL_STATUS_OPTIONS = [
	{ value: '草稿', label: '草稿' },
	{ value: '正文', label: '正文' },
] as const;

const WORKFLOW_STATUS_OPTIONS = [
	{ value: '待提交', label: '待提交' },
	{ value: '提交中', label: '提交中' },
	{ value: '审核中', label: '审核中' },
	{ value: '已完成', label: '已完成' },
	{ value: '已取消', label: '已取消' },
] as const;

const BUTTON_TEXTS = {
	AGREE: '同意',
	REJECT: '拒绝',
	SAVE: '保存',
	CLOSE: '关闭',
} as const;

const ACTIONS = {
	AGREE: '同意',
	REJECT: '拒绝',
} as const;

const API_ENDPOINTS = {
	GROUPS: '/api/SysDailyLeaveRequestBill/GetSysGroups',
} as const;

const TAB_NAMES = {
	MAIN: 'main',
	APPROVAL: '审批信息',
} as const;

const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();
const activeTab = ref(TAB_NAMES.MAIN);

// 初始化表单数据
const stateData = reactive<IViewModel<ISysDailyLeaveRequestBillVm>>({
	vmModel: {
		Entity: {
			ID: null,
			PersonId: null,
			OrgId: null,
			StaffNo: null,
			Name: null,
			LeaveType: null,
			StartTime: null,
			EndTime: null,
			Days: null,
			Reason: null,
			Approver: null,
			ApprovalTime: null,
			GroupId: null,
			BillCode: null,
			BillStatus: null,
			WorkflowStatus: null,
			Remark: null,
			SupportingDocumentId: [],
			AffectsAttendance: false,
		},
		ActionName: null,
		IsMyApprove: null,
		Remark: null,
	},
	AllSysGroups: [] as any[],
	uploadMode: false, // 是否为补传文件模式
});

// 计算属性
const isInAudit = computed(() => stateData.vmModel.Entity.WorkflowStatus === WORKFLOW_STATUS.IN_AUDIT);
const canApprove = computed(() => isInAudit.value && !!stateData.vmModel.IsMyApprove);

// 员工回显数据
const prefillPerson = computed(() => {
	const entity = stateData.vmModel.Entity;
	if (entity.PersonId && entity.Name && entity.StaffNo) {
		return {
			ID: entity.PersonId,
			Name: entity.Name,
			StaffNo: entity.StaffNo,
		};
	}
	return null;
});

// 统一的成功处理函数
const handleSuccess = () => {
	ElMessage.success(ci.proxy?.$t('message._system.common.vm.submittip') || '操作成功');
	emit('refresh');
	closeDialog();
	loading.value = false;
};

// 统一的错误处理函数
const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

// 公共的审批处理函数
const handleApproval = (actionName: string) => {
	stateData.vmModel.ActionName = actionName;
	loading.value = true;
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			api().approve(stateData.vmModel, '').then(handleSuccess).catch(handleError);
		} else {
			loading.value = false;
		}
	});
};

// 取消
const onClose = () => {
	closeDialog();
};

// 同意
const onAgree = () => {
	other.openDialog('填写同意原因', ApproveReasonDialog, null, null, '30%', (reason: string) => {
		stateData.vmModel.Remark = reason;
		handleApproval(ACTIONS.AGREE);
	});
};

// 拒绝
const onDeny = () => {
	other.openDialog('填写拒绝原因', ApproveReasonDialog, { isRequired: true }, null, '30%', (reason: string) => {
		stateData.vmModel.Remark = reason;
		handleApproval(ACTIONS.REJECT);
	});
};

// 保存补传的文件
const onSave = () => {
	loading.value = true;
	api().edit(stateData.vmModel).then(handleSuccess).catch(handleError);
};

// 初始化页面数据
const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	const routeId = useRouter().currentRoute.value.query.id;

	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
		// 检查是否为补传文件模式
		if (wtmdata.uploadMode === true) {
			stateData.uploadMode = true;
		}
	} else if (routeId) {
		stateData.vmModel.Entity.ID = routeId as any;
	}
};

// 加载页面数据
const loadPageData = async () => {
	const [groups, entityData] = await Promise.allSettled([
		other.getSelectList(API_ENDPOINTS.GROUPS, [], false),
		api().get(stateData.vmModel.Entity.ID ?? ''),
	]);

	// 处理成功的结果
	if (groups.status === 'fulfilled') stateData.AllSysGroups = groups.value;
	if (entityData.status === 'fulfilled') other.setValue(stateData.vmModel, entityData.value);
};

// 页面加载时
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		await loadPageData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

// 设置对话框头部按钮
const setupHeaderButtons = () => {
	// 如果是补传文件模式，只显示保存和关闭按钮
	if (stateData.uploadMode) {
		const headerButtons = [
			{
				text: BUTTON_TEXTS.SAVE,
				type: 'primary',
				onClick: onSave,
				visible: true,
			},
			{
				text: BUTTON_TEXTS.CLOSE,
				type: 'default',
				onClick: onClose,
				visible: true,
			},
		];
		emit('updateHeaderButtons', headerButtons);
		return;
	}

	// 正常模式：显示审批按钮
	const headerButtons = [
		{
			text: BUTTON_TEXTS.AGREE,
			type: 'primary',
			onClick: onAgree,
			visible: canApprove.value && isInAudit.value,
		},
		{
			text: BUTTON_TEXTS.REJECT,
			type: 'danger',
			onClick: onDeny,
			visible: canApprove.value && isInAudit.value,
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];

	emit('updateHeaderButtons', headerButtons);
};
</script>
